<template>
  <div class="ai-features">
    <!-- AI 功能区域 -->
    <section class="ai-section">
      <div class="ai-summary">
        <h2>今日待办总结</h2>
        <p id="daily-summary">{{ dailySummary }}</p>
      </div>
      
      <div class="ai-suggestions">
        <h2>智能建议</h2>
        <ul id="suggestions-list">
          <li v-for="(suggestion, index) in suggestions" :key="index">
            {{ suggestion }}
          </li>
        </ul>
      </div>
      
      <div class="ai-charts">
        <h2>任务统计图表</h2>
        <div class="chart-container">
          <canvas ref="completionChart" width="400" height="200"></canvas>
        </div>
        <div class="chart-container">
          <canvas ref="categoryChart" width="400" height="200"></canvas>
        </div>
      </div>
      
      <div class="ai-actions">
        <h2>AI 功能</h2>
        <div class="ai-buttons">
          <button @click="generateReminder" class="btn-ai">生成今日提醒</button>
          <button @click="getSmartSort" class="btn-ai">智能排序建议</button>
          <button @click="getTimeAnalysis" class="btn-ai">时间管理分析</button>
        </div>
      </div>
    </section>
  </div>
</template>

<script>
import { Chart, DoughnutController, BarController, CategoryScale, LinearScale, BarElement, ArcElement, Legend, Title, Tooltip } from 'chart.js';
import { aiAPI } from '../services/api.js';

// 注册Chart.js组件
Chart.register(DoughnutController, BarController, CategoryScale, LinearScale, BarElement, ArcElement, Legend, Title, Tooltip);

export default {
  name: 'AIFeatures',
  props: {
    todos: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      dailySummary: '加载中...',
      suggestions: ['加载中...'],
      completionChart: null,
      categoryChart: null
    }
  },
  async mounted() {
    // 获取 AI 功能数据
    await this.updateAIFeatures();
    // 使用 setTimeout 确保 DOM 完全渲染后再初始化图表
    setTimeout(() => {
      this.initCharts();
    }, 100);
  },
  beforeUnmount() {
    // 组件销毁前清理图表实例
    if (this.completionChart) {
      this.completionChart.destroy();
      this.completionChart = null;
    }
    if (this.categoryChart) {
      this.categoryChart.destroy();
      this.categoryChart = null;
    }
  },
  watch: {
    todos: {
      handler() {
        this.updateAIFeatures();
        // 更新图表
        this.updateCharts();
      },
      deep: true
    }
  },
  methods: {
    async updateAIFeatures() {
      // 获取每日总结
      await this.generateDailySummary();
      
      // 获取智能建议
      await this.generateAISuggestions();
    },
    
    async generateDailySummary() {
      try {
        const response = await aiAPI.getDailySummary();
        this.dailySummary = response.data.data.summary;
      } catch (error) {
        console.error('获取每日总结失败:', error);
        this.dailySummary = '获取每日总结失败';
      }
    },
    
    async generateAISuggestions() {
      try {
        const response = await aiAPI.getSmartSort();
        const suggestions = response.data.data.suggestions;
        
        // 将建议转换为字符串数组
        this.suggestions = suggestions.map(suggestion => suggestion.message);
      } catch (error) {
        console.error('获取智能建议失败:', error);
        this.suggestions = ['获取智能建议失败'];
      }
    },
    
    async generateReminder() {
      // 选择第一个未完成的任务来生成提醒
      const pendingTodo = this.todos.find(todo => !todo.completed);
      
      if (!pendingTodo) {
        alert('当前没有未完成的任务');
        return;
      }
      
      try {
        const response = await aiAPI.generateReminder(pendingTodo._id);
        const reminder = response.data.data.reminder;
        alert(reminder);
      } catch (error) {
        console.error('生成提醒文案失败:', error);
        alert('生成提醒文案失败');
      }
    },
    
    async getSmartSort() {
      try {
        const response = await aiAPI.getSmartSort();
        const suggestions = response.data.data.suggestions;
        
        if (suggestions.length > 0) {
          // 将所有建议合并为一个字符串
          const allSuggestions = suggestions.map(s => s.message).join('\n');
          alert(`智能排序建议：\n${allSuggestions}`);
        } else {
          alert('暂无智能排序建议');
        }
      } catch (error) {
        console.error('获取智能排序建议失败:', error);
        alert('获取智能排序建议失败');
      }
    },
    
    getTimeAnalysis() {
      // 使用本地数据进行时间管理分析
      const completedCount = this.todos.filter(todo => todo.completed).length;
      const totalCount = this.todos.length;
      const completionRate = totalCount > 0 ? Math.round((completedCount / totalCount) * 100) : 0;
      
      alert(`时间管理分析：您已完成 ${completedCount} 个任务，完成率为 ${completionRate}%。`);
    },
    
    initCharts() {
      // 初始化图表
      this.createCompletionChart();
      this.createCategoryChart();
    },
    
    updateCharts() {
      // 更新图表
      this.createCompletionChart();
      this.createCategoryChart();
    },
    
    createCompletionChart() {
      // 销毁之前的图表实例
      if (this.completionChart) {
        this.completionChart.destroy();
        this.completionChart = null;
      }
      
      // 确保 canvas 元素已正确初始化
      if (!this.$refs.completionChart) {
        console.warn('Completion chart canvas not found');
        return;
      }
      
      const canvas = this.$refs.completionChart;
      
      // 确保图表容器可见
      if (!canvas.parentElement || canvas.parentElement.clientWidth === 0) {
        console.warn('Chart container not visible, delaying chart creation');
        setTimeout(() => {
          this.createCompletionChart();
        }, 100);
        return;
      }
      
      // 获取数据
      const completedCount = this.todos.filter(todo => todo.completed).length;
      const pendingCount = this.todos.filter(todo => !todo.completed).length;
      
      // 确保有数据再创建图表
      if (completedCount + pendingCount === 0) {
        return;
      }
      
      // 使用 nextTick 确保 DOM 更新完成
      this.$nextTick(() => {
        try {
          // 检查组件是否仍然挂载
          if (!this.$el || !this.$el.ownerDocument) {
            console.warn('Component not mounted, skipping chart creation');
            return;
          }
          
          // 在 nextTick 中重新获取上下文
          const ctx = canvas.getContext('2d');
          if (!ctx) {
            console.warn('Unable to get 2D context for completion chart');
            return;
          }
          
          // 确保上下文有效
          if (!ctx.canvas) {
            console.warn('Canvas context is invalid');
            return;
          }
          
          this.completionChart = new Chart(ctx, {
            type: 'doughnut',
            data: {
              labels: ['已完成', '未完成'],
              datasets: [{
                data: [completedCount, pendingCount],
                backgroundColor: [
                  '#4CAF50',
                  '#F44336'
                ],
                borderWidth: 1
              }]
            },
            options: {
              responsive: true,
              maintainAspectRatio: false,
              plugins: {
                legend: {
                  position: 'bottom'
                },
                title: {
                  display: true,
                  text: '任务完成情况'
                }
              }
            }
          });
        } catch (error) {
          console.error('Error creating completion chart:', error);
        }
      });
    },
    
    createCategoryChart() {
      // 销毁之前的图表实例
      if (this.categoryChart) {
        this.categoryChart.destroy();
        this.categoryChart = null;
      }
      
      // 确保 canvas 元素已正确初始化
      if (!this.$refs.categoryChart) {
        console.warn('Category chart canvas not found');
        return;
      }
      
      const canvas = this.$refs.categoryChart;
      
      // 确保图表容器可见
      if (!canvas.parentElement || canvas.parentElement.clientWidth === 0) {
        console.warn('Chart container not visible, delaying chart creation');
        setTimeout(() => {
          this.createCategoryChart();
        }, 100);
        return;
      }
      
      // 获取数据
      const workCount = this.todos.filter(todo => todo.category === 'work').length;
      const studyCount = this.todos.filter(todo => todo.category === 'study').length;
      const lifeCount = this.todos.filter(todo => todo.category === 'life').length;
      
      // 确保有数据再创建图表
      if (workCount + studyCount + lifeCount === 0) {
        return;
      }
      
      // 使用 nextTick 确保 DOM 更新完成
      this.$nextTick(() => {
        try {
          // 检查组件是否仍然挂载
          if (!this.$el || !this.$el.ownerDocument) {
            console.warn('Component not mounted, skipping chart creation');
            return;
          }
          
          // 在 nextTick 中重新获取上下文
          const ctx = canvas.getContext('2d');
          if (!ctx) {
            console.warn('Unable to get 2D context for category chart');
            return;
          }
          
          // 确保上下文有效
          if (!ctx.canvas) {
            console.warn('Canvas context is invalid');
            return;
          }
          
          this.categoryChart = new Chart(ctx, {
            type: 'bar',
            data: {
              labels: ['工作', '学习', '生活'],
              datasets: [{
                label: '任务数量',
                data: [workCount, studyCount, lifeCount],
                backgroundColor: [
                  '#2196F3',
                  '#FF9800',
                  '#9C27B0'
                ],
                borderWidth: 1
              }]
            },
            options: {
              responsive: true,
              maintainAspectRatio: false,
              plugins: {
                legend: {
                  display: false
                },
                title: {
                  display: true,
                  text: '任务分类统计'
                }
              },
              scales: {
                y: {
                  beginAtZero: true,
                  ticks: {
                    precision: 0
                  }
                }
              }
            }
          });
        } catch (error) {
          console.error('Error creating category chart:', error);
        }
      });
    }
  }
}
</script>

<style scoped>
.ai-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 30px;
}

.ai-summary, .ai-suggestions {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.ai-summary h2, .ai-suggestions h2 {
  color: #3498db;
  margin-bottom: 15px;
}

#daily-summary {
  font-style: italic;
  color: #7f8c8d;
  line-height: 1.6;
}

#suggestions-list {
  list-style-type: none;
}

#suggestions-list li {
  padding: 10px;
  margin-bottom: 10px;
  background-color: #ecf0f1;
  border-radius: 4px;
  border-left: 4px solid #3498db;
}

.ai-charts {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
  grid-column: span 2;
}

.ai-charts h2 {
  color: #3498db;
  margin-bottom: 15px;
}

.chart-container {
  margin-bottom: 20px;
  position: relative;
  height: 200px;
}

.ai-actions {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
  grid-column: span 2;
}

.ai-actions h2 {
  color: #3498db;
  margin-bottom: 15px;
}

.ai-buttons {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.btn-ai {
  padding: 10px 20px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
  font-weight: 500;
}

.btn-ai:hover {
  background-color: #2980b9;
}

@media (max-width: 768px) {
  .ai-section {
    grid-template-columns: 1fr;
  }
  
  .ai-actions {
    grid-column: span 1;
  }
  
  .ai-buttons {
    flex-direction: column;
  }
  
  .btn-ai {
    width: 100%;
  }
}
/* 夜间模式样式 */
.dark-mode .ai-summary,
.dark-mode .ai-suggestions,
.dark-mode .ai-charts,
.dark-mode .ai-actions {
  background-color: #2d2d2d;
  color: #e0e0e0;
  box-shadow: 0 2px 5px rgba(0,0,0,0.3);
}

.dark-mode .ai-summary h2,
.dark-mode .ai-suggestions h2,
.dark-mode .ai-charts h2,
.dark-mode .ai-actions h2 {
  color: #64b5f6;
}

.dark-mode #daily-summary {
  color: #aaa;
}

.dark-mode #suggestions-list li {
  background-color: #424242;
  border-color: #1976d2;
}

.dark-mode .btn-ai {
  background-color: #1976d2;
}

.dark-mode .btn-ai:hover {
  background-color: #1565c0;
}
</style>